package com.example.demo.controller;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;


import java.io.IOException;
import java.util.Base64;
import java.util.Map;
import java.util.HashMap;
import java.util.List;

//请求地址
//http://127.0.0.1:8080/image/recognize

@Controller
@RequestMapping("/api/python/image")
public class ImageRecognizeController {
    private final String PYTHON_API_URL = "http://localhost:8000/predict_image"; // Python API的URL
    private final ObjectMapper objectMapper = new ObjectMapper(); // 用于将Map转换为JSON字符串
    @PostMapping("/recognize")
    @ResponseBody
    public String recognizeImage(@RequestParam("file") MultipartFile file) throws IOException, JsonProcessingException {
        // 创建 RestTemplate 实例
        RestTemplate restTemplate = new RestTemplate();

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        // 创建 MultiValueMap 来存储文件数据
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("file", new ByteArrayResource(file.getBytes()) {
            @Override
            public String getFilename() {
                return file.getOriginalFilename();
            }
        });

        // 创建 HttpEntity 对象，包含请求体和请求头
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);

        //
//        // 发送请求到 Python API，期望接收到图像数据作为字节数组
//        ResponseEntity<byte[]> response = restTemplate.exchange(
//                PYTHON_API_URL,
//                HttpMethod.POST,
//                requestEntity,
//                byte[].class
//        );
////        // 打印返回的响应体（字节数组）
////        byte[] responseBody = response.getBody();
////        System.out.println("Response Body (byte[]): " + new String(responseBody, StandardCharsets.UTF_8));
//        // 确保响应体存在且是有效的字节数组
//        byte[] responseBody = response.getBody();
//        if (responseBody != null) {
//            // 将返回的图像字节数组添加到模型中，供视图使用
//            String base64Image = Base64.getEncoder().encodeToString(responseBody);
//            model.addAttribute("image", base64Image);
//        } else {
//            // 处理没有返回数据的情况
//            model.addAttribute("error", "No image data returned from API");
//        }
//        // 返回显示图像的视图
//        return "imageView";  // 这个视图需要在模板引擎中定义（比如 Thymeleaf 或 JSP）



        // 发送请求到 Python API，期望接收到包含图像和结果的 Map
        ResponseEntity<Map> response = restTemplate.exchange(
                PYTHON_API_URL,
                HttpMethod.POST,
                requestEntity,
                Map.class
        );

        // 确保响应体存在且包含正确的数据
        Map<String, Object> responseBody = response.getBody();
        if (responseBody != null && responseBody.containsKey("image") && responseBody.containsKey("result")) {
            // 创建一个包含图像和识别结果的 JSON 响应
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("image", responseBody.get("image"));
            resultMap.put("result", responseBody.get("result"));
            System.out.println("Response Body (Map): " + resultMap);
            // 将 Map 转换为 JSON 字符串并返回
            return objectMapper.writeValueAsString(resultMap);
        } else {
            // 处理没有返回数据或格式不正确的情况
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "Invalid response from API");
            return objectMapper.writeValueAsString(errorResponse);
        }
    }
}

